package com.sinodata.bsm.cicp.util.telnet;

import java.io.IOException;

import de.mud.ssh.SshWrapper;

/**
 * 利用 JTA 实现的 SSH1.5.
 *
 * @author thomas.h.zhang
 */
public class JtaSSH extends SshWrapper implements Telnet {
    /**
     * 超时时长.
     */
    private static final int timeoutsecond = 30; // 10's

    public JtaSSH() {
    }

    //标记此连接是否可用
    private boolean isValid = true;

    public void setIsValid(boolean isValid) {
        this.isValid = isValid;
    }

    public boolean getIsValid() {
        return this.isValid;
    }

    public void login(String user, String pwd, String prompt) throws TelnetException {
        try {
            this.handler.setLogin(user);
            this.handler.setPassword(pwd);
            this.setPrompt(prompt);

            this.sendOnly("");
        } catch (IOException e) {
            throw new TelnetException("login on " + host + ":" + port + " " + user + "/" + prompt + " exception: ", e);
        }

        // 接收登录提示
        // Last login: Tue Jul 3 23:52:42 from 192.168.9.29
        // Sun Microsystems Inc. SunOS 5.10 Generic January 2005
        //this.runTask(null);
    }

    /**
     * Send a command to the remote host. A newline is appended and if a prompt
     * is set it will return the resulting data until the prompt is encountered.
     *
     * @param cmd
     *            the command
     * @return output of the command or null if no prompt is set
     */
    private void sendOnly(String cmd) throws IOException {
        byte arr[];
        arr = (cmd + "\n").getBytes();
        // no write until authorization is done
        for (int i = 0; i < arr.length; i++) {
            switch (arr[i]) {
                case 10: /* \n -> \r */
                    arr[i] = 13;
                    break;
            }
        }
        handler.sendData(new String(arr));
    }

    /**
     * 发送shell指令到目的主机.
     */
    public void sendCmd(String cmd) throws IOException {
        sendOnly(cmd);
    }

    /**
     * 接受shell执行结果.
     */
    public String recvResp() throws IOException {
        if (getPrompt() != null) {
            return waitfor(getPrompt());
        }
        return null;
    }

    /**
     * 发送取消执行shell的指令, 及发送一个^C
     */
    public void cancel() throws IOException {
        sendCmd("\003"); // ^C
        recvResp();
    }

    public void runLogin(String user, String pwd, String prompt) throws TelnetException {
        LoginTask task = new LoginTask(this, user, pwd, prompt);
        task.start();

        int count = 0;
        // wait until last task is complete
        while (!task.isComplete() || task.isActive()) {
            try {
                Thread.sleep(1000);
                count++;
                if (count >= timeoutsecond) {
                    Thread.interrupted();
                    task.stop();
                    throw new TelnetTaskTimeoutException("login timeout: " + timeoutsecond + "'s");
                }
            } catch (InterruptedException e) {
            }
        }
    }

    public String runTask(String shell) throws TelnetException {
        TelnetTask task = new TelnetTask(this, shell);
        task.start();

        int count = 0;
        // wait until last task is complete
        while (!task.isComplete() || task.isActive()) {
            try {
                Thread.sleep(1000);
                count++;
                if (count >= timeoutsecond) {
                    try {
                        cancel();
                    } catch (IOException e) {
                    }
                    Thread.interrupted();
                    task.stop();
                    throw new TelnetTaskTimeoutException("execute command:[" + task.getCmd() + "] timeout:" + timeoutsecond + "'s");
                }
            } catch (InterruptedException e) {
            }
        }

        return task.getShellOut();
    }

    public static void main(String[] args) throws Exception {
        String host = "192.168.99.115";
        int port = 22;
        String username = "root";
        String password = "root";
        String prompt = "[root@ksoftnms01 ~]# ";
        //String username = "ultranms";
        //String password = "ultranms2008";
        //String prompt = "$";
        //        String cmd = "ls -l";
        String recv;

        JtaSSH ssh = new JtaSSH();
        try {
            ssh.connect(host, port);
            //ssh.login(username, password, prompt);
            // 接收登录提示
            //ssh.runTask(null);
            ssh.runLogin(username, password, prompt);

            // ssh.sendCmd("");
            // recv = ssh.recvResp();
            // System.out.println("shell out: [" + recv + "]");

            recv = ssh.send("netstat -i");
            System.out.println("shell out: [" + recv + "]");

            //            recv = ssh.send("LANG=C;export LANG");
            //            System.out.println("shell out: [" + recv + "]");
            //
            //            recv = ssh.send("ls -l");
            //            System.out.println("shell out: [" + recv + "]");
            //            // writeToFile("ls.txt", recv);
            //
            //            recv = ssh.send("df -k");
            //            System.out.println("shell out: [" + recv + "]");
            //
            //            recv = ssh.runTask("vmstat 1 5");
            //            System.out.println("shell out: [" + recv + "]");
        } finally {
            ssh.disconnect();
        }
    }

}
